package com.k8.common.factroy.loader;

import com.k8.common.ioc.BeanPostProcessor;
import com.k8.common.factroy.instance.InstanceStrategyFactory;
import lombok.Getter;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ExtensionDirector implements ExtensionAccessor {
    @Getter
    List<BeanPostProcessor> beanPostProcessors;
    @Getter
    InstanceStrategyFactory instanceStrategyFactory;
    private ConcurrentHashMap<Class<?>, ExtensionLoader<?>> extensionLoaderMap = new ConcurrentHashMap<>(64);

    @Override
    public <T> ExtensionLoader<T> getExtensionLoader(Class<T> clazz) {
        if (!clazz.isInterface()) return null;
        ExtensionLoader<T> k8ExtensionLoader = (ExtensionLoader<T>) extensionLoaderMap.get(clazz);
        if (k8ExtensionLoader == null) {
            synchronized (extensionLoaderMap) {
                k8ExtensionLoader = (ExtensionLoader<T>) extensionLoaderMap.get(clazz);
                if (k8ExtensionLoader == null) {
                    k8ExtensionLoader = new ExtensionLoader<>(clazz, this, instanceStrategyFactory);
                    extensionLoaderMap.put(clazz, k8ExtensionLoader);
                }
            }
        }
        return k8ExtensionLoader;
    }


    public ExtensionDirector(InstanceStrategyFactory instanceStrategyFactory) {
        this.instanceStrategyFactory = instanceStrategyFactory;
        ExtensionLoader<BeanPostProcessor> beanPostProcessorsLoader = this.getExtensionLoader(BeanPostProcessor.class);
        this.beanPostProcessors = beanPostProcessorsLoader.getExtensions();
        instanceStrategyFactory.setBeanPostProcessors(this.beanPostProcessors);
    }


    @Override
    public ExtensionDirector getExtensionDirector() {
        return this;
    }


}
